import subprocess
import datetime
import os

script_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(script_dir)

def run_command(command):
    result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    return result.stdout.splitlines()

# 获取docker ps -a的输出
ps_command = "docker ps -a"
ps_output = run_command(ps_command)

# 获取docker images的输出
images_command = "docker images"
images_output = run_command(images_command)

# 将结果存入列表
docker_ps_list = ps_output

docker_images_list = images_output

# 解析docker ps -a的输出为列表
container_line_data = []
for line in docker_ps_list:
    lines = line.split("   ")
    data = [x for x in lines if x.strip() != ""]
    container_line_data.append(data)
images_line_data = [] 
for line in docker_images_list:
    lines =line.split("   ")
    data = [x for x in lines if x != ""]
    images_line_data.append(data)
for data in images_line_data[1:]:
    image = data[0]
    tag = data[1]
    # 创建 backup_image.sh 文件
    backup_file_path = os.path.join(parent_dir,f"save_image-{image.replace('/','_')}_{tag.replace(' ','')}.sh")
    with open(backup_file_path, "w") as file:
        file.write("#!/bin/bash\n\n")
        file.write("docker images \n")
        # 获取当前日期
        current_date_time = datetime.datetime.now()
        # 将当前日期格式化为所需的字符串形式
        date_time_string = current_date_time.strftime("%Y_%m%d_%H%M_%S")
        # 生成docker save命令
        tar_file_path = os.path.join(parent_dir,"backup_images",f"{image.replace('/','_')}_{tag.replace(' ','')}.tar")
        save_cmd = f"docker save -o {tar_file_path} {image}:{tag.replace(' ','')}"
        
        # 将保存命令写入文件
        file.write(save_cmd + "\n")
        
# Print the location of the generated file
# print(f"Backup script has been created at: {backup_file_path}")